export default {
  /**
   * param 将要转为URL参数字符串的对象
   * key URL参数字符串的前缀
   * encode true/false 是否进行URL编码,默认为true
   *
   * return URL参数字符串
   */
  urlEncode: function (param, key, encode) {
    if (param == null) {
      return '';
    }

    var paramStr = '';
    var t = typeof (param);

    if (t === 'string' || t === 'number' || t === 'boolean') {
      paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
    } else {
      for (var i in param) {
        var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
        paramStr += this.urlEncode(param[i], k, encode);
      }
    }

    return paramStr;
  },
    /**
     * url解析
     * @param url
     * @returns {{href: string, hash: string, host: string, hostname: string, origin: *|string, pathname: string, port: string, search: string, protocol: string, params}}
     */
    parseURL: function (url) {
        var a;
        if (typeof window.URL === "function" || (navigator.userAgent.indexOf('MSIE') !== -1 && typeof URL === 'object')) {
            a = new URL(url)
        } else {
            a =  document.createElement('a');
            a.href = url;
        }

        return {
            href: a.href,
            hash: a.hash,
            host: a.host,
            hostname: a.hostname,
            origin: a.origin,
            pathname: a.pathname,
            port: a.port,
            search: a.search,
            protocol: a.protocol,
            params: (function(){
                var ret = {},
                    seg = a.search.replace(/^\?/,'').split('&'),
                    len = seg.length, i = 0, s;
                for (;i<len;i++) {
                    if (!seg[i]) { continue; }
                    s = seg[i].split('=');
                    ret[s[0]] = decodeURIComponent(s[1]);
                }
                return ret;
            })(),
        }
    },
}
